package org.ns.tomdog.server.support;

import org.ns.tomdog.server.Container;
import org.ns.tomdog.server.WebAppContainer;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ContainerStartup implements Container {
    private Map<String, WebAppContainer> webAppContainerMap = new ConcurrentHashMap<>();
    private String defaultWebapp = "localhost";

    public ContainerStartup(List<WebAppContainer> webAppContainers, String defaultWebapp) {
        for (WebAppContainer webAppContainer : webAppContainers) {
            webAppContainerMap.put(webAppContainer.getHost(), webAppContainer);
        }
        this.defaultWebapp = defaultWebapp;
    }

    @Override
    public WebAppContainer getWebAppContainer(String domain) {
        WebAppContainer webAppContainer = webAppContainerMap.get(domain);
        if (webAppContainer == null) {
            webAppContainer = webAppContainerMap.get(defaultWebapp);
        }

        return webAppContainer;
    }

    @Override
    public void init() {
        for (WebAppContainer webAppContainer : webAppContainerMap.values()) {
            webAppContainer.init();
        }
    }

    @Override
    public void start() {
        for (WebAppContainer webAppContainer : webAppContainerMap.values()) {
            webAppContainer.start();
        }
    }
}
